<?php
//乐观锁实现秒杀
class watch 
{
   public function log($content){
    header("Content-type: text/html; charset=utf-8");
    $file  = 'log.txt';
    if($f  = file_put_contents($file, $content,FILE_APPEND)){// 这个函数支持版本(PHP 5)
      echo "写入成功。<br />";
    }
     }
}
header("content-type:text/html;charset=utf-8");  
$redis = new \redis();
$result = $redis->connect('127.0.0.1', 6379); 
$mywatchkey = $redis->get("zdk1");  //设置一个字段https://wenku.baidu.com/view/65dd917bb5daa58da0116c175f0e7cd185251802.html
$rob_total = 500;   //抢购数量
if($mywatchkey<$rob_total){
    $redis->watch("zdk1");  //监听字段
    $redis->multi();  //开始
    //插入抢购数据  
    $user_id="user_id_".mt_rand(1999999, 9999999);//模拟用户id生成
    $redis->hSet("mywatchlist",$user_id,time());//抢购 添加用户  
    $redis->set("zdk1",$mywatchkey+1);  //抢购+1
    $rob_result = $redis->exec();  //事务 结束
    if($rob_result){  
        //数据无冲突 事物已提交成功
        $mywatchlist = $redis->hGetAll("mywatchlist");  //获取所有抢购成功的用户
        $content= $user_id."抢购成功 剩余数量：".($rob_total-$mywatchkey-1)."\n";
        $a=new watch;
        $a->log($content);
        // $content=json_encode($mywatchlist)."\n"; 
  
    }else{  
        //数据有冲突,事务没有提交,乐观锁
          $a=new watch;
         $a->log("手气不好，再抢购！");
        echo "手气不好，再抢购！";exit;  
    }  
} else{
      $a=new watch;
         $a->log("手气不好，再抢购！\n");
        // $mywatchlist = $redis->hGetAll("mywatchlist");  //获取所有抢购成功的用户
        // //所有抢购成功的用户
        // $content=json_encode($mywatchlist)."\n"; 
        //  $a->log($content);
        echo "手气不好，再抢购！";exit; 
}
 
